package com.example.mydemo.controller.hc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mydemo.entity.SysParam;
import com.example.mydemo.mapper.SysParamMapper;
import com.example.mydemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class RedisDemoController {
    @Autowired
    private SysParamMapper sysParamMapper;
    @Autowired
    private RedisUtil redisUtil;

    // 假设已有 SysParam 实体类和服务类

    /**
     * 直接修改数据库参数（不操作 Redis）
     */
    @PostMapping("/update-db")
    public ResponseEntity<Boolean> updateDbParam(
            @RequestParam String paramCode,
            @RequestParam String paramName,
            @RequestParam String paramValue
    ) {                SysParam sysParam = new SysParam();
        sysParam.setParamValue(paramValue);
        sysParam.setParamName(paramName);
        int updated = sysParamMapper.update(
                sysParam, // 显式传递实体对象
                new UpdateWrapper<SysParam>().eq("param_code", paramCode)
        );
        return ResponseEntity.ok(updated > 0);
    }

    /**
     * 同步 Redis 并返回最新值
     */
    @GetMapping("/sync-redis")
    public ResponseEntity<String> syncRedis(@RequestParam String paramCode) {
        // 1. 从数据库查询最新值
        SysParam param = sysParamMapper.selectOne(
                new QueryWrapper<SysParam>().eq("param_code", paramCode)
        );
        if (param == null) {
            return ResponseEntity.notFound().build();
        }

        // 2. 更新 Redis
        String cacheKey = paramCode;
        redisUtil.set(cacheKey, param.getParamValue());

        // 3. 返回最新值
        return ResponseEntity.ok(param.getParamValue());
    }
}
